import os

from funasr import AutoModel
from funasr.utils.postprocess_utils import rich_transcription_postprocess

from ai_server.audio_format.opus import Opus_Encode
from utils.util import Util


class Fun_Asr:
    def __init__(self,config):
        self.dir = config.get("output_dir")
        self.current_dir = os.path.dirname(os.path.abspath(__file__))
        self.model_dir = os.path.join(self.current_dir, 'model')
        self.model = AutoModel(
            model=self.model_dir,

            vad_kwargs={
                "threshold": 0.5,
                "min_silence_duration_ms": 5000,
                "min_speech_duration_ms": 200,
                "max_speech_duration_s": 3000,
            },
            hub="hf",
            disable_update=True
        )

    def opus_to_text(self, opus_data):
        opus = Opus_Encode()
        opus.opus_to_audio(output_path="./ai_server/asr/fun_asr/temp/test.wav", opus_datas=opus_data)
        res = self.model.generate(input="./ai_server/asr/fun_asr/temp/test.wav",
                                  language="auto",
                                  use_itn=True,
                                  )
        return rich_transcription_postprocess(res[0]["text"])


